package common;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 	Sami Diab
 * @since 	13/11/2011
 * Contient des fonctions qui concernent la manipulation de fichier
 */
public class FileManipulation {
	
	//Returns only files in a folder
	public static List<String> getFileNames(String path)
	{
			
    	File dir = new File(path);  //eg. /WEB-INF/jsp/my.jsp
    	
    	//List of files
    	File list[] = dir.listFiles();
    	
    	//List of files name
    	List<String> fileNamelist = new ArrayList<String>();
    	
    	for(int i = 0; i < list.length; i++)
    	{
    		if(list[i].isFile())
    		{
    			fileNamelist.add(list[i].getName());
    		}
    	}
    	
    	return fileNamelist;
    	
    	
		//File jsp = new File(/getRealPath("/WebContent/Templates/default.htm"));  //eg. /WEB-INF/jsp/my.jsp
    	//File directory = jsp.getParentFile();
    	//File[] list = directory.listFiles();
    	
    	
		//String repertoireCourant = System.getProperty("user.dir");// + "/WebContent/Templates";
		  
		//Directory htmlTemplates = path;//request.getRealPath(pathToJspInWebapp);  //eg. /WEB-INF/jsp/my.jsp
		
		/*File defaultTemplate  = new File(path);
		File htmlTemplates = defaultTemplate.getParentFile().getParentFile();
		
		File [] files = htmlTemplates.listFiles();
		String [] fileNames = new String[files.length];
    	for (int i = 0; i < files.length; i++) {
    		
    		 fileNames[i] = files[i].getName();
    	}
		
		return fileNames;*/	
	}

	//Returns the content of a file in a String
	public static String readFile(String path) throws IOException {
		  FileInputStream stream = new FileInputStream(new File(path));
		  try {
		    FileChannel fc = stream.getChannel();
		    MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
		    /* Instead of using default, pass in a decoder. */
		    return Charset.defaultCharset().decode(bb).toString();
		  }
		  finally {
		    stream.close();
		  }
		}

}


